/**
 * Created by lx on 2018/4/3.
 */
CommonUtils.regNamespace("com.im.projectInfoManage.needProgressManage");

$(function() {
    com.im.projectInfoManage.needProgressManage.invoke.init();
});

com.im.projectInfoManage.needProgressManage.invoke = function() {
    var client = new com.im.common.ajax();

    /**
     * 页面初始化
     * @private
     */
    function _init() {
        //初始化时间、复选框、下拉框、公共组件等事件和样式
        _initCommpentAction();
        //表单验证
        _initFormValidate();
        //规划类型列表
        _queryPlanTypeList();
        //项目信息进度列表查询
        $("#vQuerySubjects").on("click", function () {
            _querySubjects(1);
        }).trigger("click");
        //新增项目进度
        $("#vShowProgressModal").on("click", _showProgressModal);
        $("#vAddProgress").on("click", _addEditProgress);
        //条件重置
        $("#vResetCond").on("click", _resetCond);
        //报送
        $('#vSubmit').click(function (){
        	_SubmitPro(true);
        });
        //取消报送
        $('#vCancleSubmit').click(function (){
        	_SubmitPro(false);
        });
    }

    function _initCommpentAction() {
        //时间插件
        $('#startDatepicker,#endDatepicker').datepicker({
            autoclose: true
        });

        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        });

        //下拉框
        $('.select2').select2();
        
        //所属规划
        $("#vPlanProjClass").constantCommpent({
    	    elmIdSel : "vPlanProjClass",//需要展示的位置下拉框
    	    constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
    	    callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
    	    	_querySubjects(1);
    	    }
    	});

        //建设单位查询组件
        $("#vCompanyName").unitselCommpent({
            elmIdSel : "vCompanyName",//需要展示的位置下拉框
            unitType : "10",//单位类型 为空的时候全部查询
            callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
            	_querySubjects(1);
            }
        });

        //项目查询组件
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal2' ></div>")));
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal3' ></div>")));
        $("#vQuerySubject").click(function() {
            $("#vQuerySubject").itemSearchCommpent({
                elmIdOut : "vSubjectName2",//组织树单击之后回填的文本框（input）
                elmIdModal : "modal2",//用户选择
                elmIdOrgModal : "modal3",//组织查询
                callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
                    $("#vSubjectName2").attr("vaSubjectId", projectId);
                }
            });
        });

        //工程查询组件
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal4' ></div>")));
        $("body").append($($.parseHTML("<div class='modal fade bs-example-modal-lg' id='modal5' ></div>")));
        $("#vQueryProject").click(function() {
            $("#vQueryProject").projectSearchCommpent({
                elmIdOut : "vProjectName",//组织树单击之后回填的文本框（input）
                elmIdModal : "modal4",//用户选择
                elmIdOrgModal : "modal5",//组织查询
                callbackFunc: function (projectId, projectName) {//组织树单击之后回调函数
                    $("#vProjectName").attr("vaProjectId", projectId);
                }
            });
        });
    }
    /**
     * 报送/取消报送项目
     * @param object
     * @private
     */
    function _SubmitPro(type) {
    	var impleProjIds = new Array();
    	$.each($('#vSubjectsTable').datagrid('getChecked'), function(index, item){
    		impleProjIds.push(item.impleProjId);
        });
    	if(impleProjIds.length == 0){
    		toastr.info('请选择项目');
        	return;
    	}
    	if(type){
    		com.im.common.confirm("确认报送项目", null, function () {
                var req = {};
                req.impleProjIds = impleProjIds.join(',');
                req.ifSubmit = '1';
                var resp = client.callAsJson("projectInfoService/updateProjPlanDeclareSet", req);
                if (!resp.success) {
                    toastr.error(resp.resultMsg);
                    return;
                }
                toastr.success("报送项目成功");
                _querySubjects(1);
            });
    	}else{
    		com.im.common.confirm("确认取消报送项目", null, function () {
                var req = {};
                req.impleProjIds = impleProjIds.join(',');
                req.ifSubmit = '0';
                var resp = client.callAsJson("projectInfoService/updateProjPlanDeclareSet", req);
                if (!resp.success) {
                    toastr.error(resp.resultMsg);
                    return;
                }
                toastr.success("取消报送项目成功");
                _querySubjects(1);
            });
    	}
        
    }

    /**
     * 表单验证
     * @param $form
     * @returns {boolean}
     * @private
     */
    function _formValidate($form) {
        $form.data("bootstrapValidator").validate();
        return $form.data("bootstrapValidator").isValid();
    }

    /**
     * 表单验证初始化
     * @private
     */
    function _initFormValidate(flag) {
        $("#vAddProgressForm").bootstrapValidator({
            live: 'enabled',
            excluded: [],
            feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
            fields: {
                vProjectName: {validators: {notEmpty:{message:"请选择规划工程"}}},
                vSubjectName2: {validators: {notEmpty:{message:"请选择实施项目名称"}}}
            }
        });

        if(flag == undefined) {
            $('#addEditModal').on('hidden.bs.modal', function () {
                $('#vAddProgressForm').data('bootstrapValidator').destroy();
                $('#vAddProgressForm').data('bootstrapValidator', null);
                _initFormValidate("again");
            });
        }
    }

    /**
     * 获取规划类型列表
     * @private
     */
    function _queryPlanTypeList() {
    	$("#vPlanTypes").constantCommpent({
    	    elmIdSel : "vPlanTypes",//需要展示的位置下拉框
    	    constParamCode : "PLAN_PROJ_CLASS",//需要加载的常量编码
    	    callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
    	    	_querySubjects(1);
    	    }
    	});
    }

    /**
     * 项目信息进度列表查询
     * @private
     */
    function _querySubjects(index) {
        if(com.im.projectInfoManage.needProgressManage.subjectColumns == undefined) {
            com.im.projectInfoManage.needProgressManage.subjectColumns = [
                [{field:'全选',title:"全选",width:30,checkbox:true,rowspan:2,fitColumns:true},
                    {field:'vaSeq',title:"序<br/>号",width:30,rowspan:2,fitColumns:true,formatter: function(value,row,index){return index + 1;}},
                    {field:'planProjName',title:"工程名称",width:100,rowspan:2,align:'left',fitColumns:true},
                    {field:'impleProjName',title:"实施项目名称",width:100,rowspan:2,fitColumns:true,align:'left', formatter: function(value,row,index){
                        if(row.subList && row.subList.length > 0) {
                            if(row.isExtend) {
                                return  "<a href='javascript:void(0)' onclick='com.im.projectInfoManage.carrayProjectManage.invoke.showSSubject("+ index +");'><i class='fa fa-minus-square-o'></i> " +  value + "</a>";
                            } else {
                                return  "<a href='javascript:void(0)' onclick='com.im.projectInfoManage.carrayProjectManage.invoke.showSSubject("+ index +");'><i class='fa fa-plus-square-o'></i> " +  value + "</a>";
                            }
                        } else {
                            return value;
                        }
                    }
                    },
                    {field:'developOrgName',title:"建设单位",width:80,rowspan:2,align:'left',fitColumns:true},
                    {title:"建设年限",colspan:2,fitColumns:true},
                    {field:'leadingPersonName',title:"项目<br/>负责人",rowspan:2,fitColumns:true},
                    {field:'linkmanName',title:"项目<br/>联系人",rowspan:2,fitColumns:true},
                    {title:"阶段资金构成（单位：万元）",colspan:6,fitColumns:true},
                    {field:'contentScale',title:"主要建设内容",rowspan:2,fitColumns:true,align:'left',formatter: function(value,row,index){
                        if(value){
                            if(value.length > 20){
                                return "<a style='font-size:12px;' href='javascript:;' data-toggle='modal' onclick='com.im.projectInfoManage.carrayProjectManage.invoke.showSubjectContent("+ index +");'>" + value.substr(0,20) + "...</a>";
                            }else{
                                return "<a style='font-size:12px;' href='javascript:;' data-toggle='modal' onclick='com.im.projectInfoManage.carrayProjectManage.invoke.showSubjectContent("+ index +");'>" + value + "</a>";
                            }
                        }
                    }},
                    {field:'projStageClassName',title:"当前阶段",width:100,align:'left',rowspan:2,fitColumns:true},
                    {field:'impleSituation',title:"进展描述",width:100,rowspan:2,align:'left',fitColumns:true,formatter: function(value,row,index){
                        if(value && value.length > 10){
                            return value.substr(0,10) + "...";
                        }else{
                            return value;
                        }
                    }},
                    {field:'preWorkSituation',title:"前期工作情况",width:100,rowspan:2,align:'left',fitColumns:true,formatter: function(value,row,index){
                        return value.replace(/;/g,'<br/>');
                    }},
                    {field:'statusName',title:"状态",width:50,rowspan:2,fitColumns:true},
                    {field:'ifSubmitName',title:"是否报送",width:50,rowspan:2,fitColumns:true}],
                [{field:'startDt',title:"开工年",fitColumns:true},
                    {field:'endDt',title:"完工年",fitColumns:true},
                    {field:'total',title:"合计",fitColumns:true},
                    {field:'fundSourceBu',title:"部补助",fitColumns:true},
                    {field:'fundSourceSheng',title:"省财政",fitColumns:true},
                    {field:'fundSourceGao',title:"政府融资",fitColumns:true},
                    {field:'fundSourceShi',title:"市州配套",fitColumns:true},
                    {field:'fundSourceQi',title:"企业自筹",fitColumns:true}]
            ];
        }

        var req = {};
        req.pageInfo = {};
        req.pageInfo.pageNumber = index;
        req.pageInfo.pageSize = 20;
        req.impleProjName = $("#vSubjectName").val();
        req.developOrg = $("#vCompanyName option:selected").attr("value");
        req.planProjClass = $("#vPlanProjClass option:selected").attr("value");
        var resp = client.callAsJson("projectInfoService/queryImpleDeclareSetList", req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }

        $("#vSubjectsTable").empty();
        $("#vSubjectsTable").datagrid({
    	    nowrap:false,
    	    fitColumns:true,
        	pagination:true,
        	columns:com.im.projectInfoManage.needProgressManage.subjectColumns,
        	data:resp.result
        });
        var p = $('#vSubjectsTable').datagrid('getPager');
        $(p).pagination({
            total : resp.result.total,
            pageSize : resp.result.pageSize,
            pageNumber : resp.result.pageNumber,
            pageList : [20 , 40],
            beforePageText: '第',
            afterPageText: '页    共 {pages}  页',
            displayMsg: '当前显示 {from} - {to} 条记录 共 {total}  条记录',
            onSelectPage:function(pageNumber, pageSize){
                _querySubjects(pageNumber, false);
            }
        });
    }

    /**
     * 修改项目进度
     * @private
     */
    function _showEditSubject(index) {
        var vaSubject = $('#vSubjectsTable').datagrid('getData').rows[index];
        $("#vProgressId").val(vaSubject.declareSetId);
        $("#vProjectName").val(vaSubject.planProjName);
        $("#vSubjectName2").val(vaSubject.impleProjName);
        $("#vSubjectId").val(vaSubject.impleProjId);
        if(vaSubject.ifSubmit == "1") {
            $("#vBs").attr("checked", true);
        }
        $("#addEditModal").modal("show");
    }

    /**
     * 新增项目进度 作废
     * @private
     */
    function _showProgressModal() {
        $("#vProjectName").val("");
        $("#vSubjectName2").val("");
        $("#addEditModal").modal("show");
    }

    /**
     * 新增项目进度
     * @private
     */
    function _addEditProgress() {
        if(!_formValidate($("#vAddProgressForm"))) {
            return;
        }
        var req = {};
        if($("#vBs").is(":checked")) {
            req.ifSubmit = "1";
        } else {
            req.ifSubmit = "0";
        }

        var url = null;
        var resultMsg = null;
        if(req.vaProgressId == null && req.vaProgressId == "") {
            req.declareSetId = $("#vProgressId").val();
            req.planProjClass = $("#vPlanTypes option:selected").attr("vaPlanTypeId");
            req.planProjName = $("#vProjectName").val();
            req.impleProjName = $("#vSubjectName2").val();
            req.impleProjId = $("#vSubjectId").val();
            url = "projectInfoService/addProjPlanDeclareSet";
            resultMsg = "新增成功"
        } else {
            req.impleProjId = $("#vSubjectId").val();
            url = "projectInfoService/updateProjPlanDeclareSet";
            resultMsg = "修改成功"
        }
        var resp = client.callAsJson(url, req);
        if (!resp.success) {
            toastr.error(resp.resultMsg);
            return;
        }
        toastr.success(resultMsg);
        _querySubjects(1);
        $("#addEditModal").modal("hide");
    }

    /**
     * 条件重置
     * @private
     */
    function _resetCond() {
        $("#vPlanProjClass").val("").trigger("change");
        $("#vCompanyName").val("").trigger("change");
        $("#vSubjectName").val("");
        _querySubjects(1);//重复调用
    }
    
    return {
        init : _init,
        showEditSubject : _showEditSubject
    }
}();
